package com.hsogoo.collate.controller;

import com.hsogoo.collate.domain.CollateConfig;
import com.hsogoo.collate.domain.CollateQueryReq;
import com.hsogoo.collate.domain.DataSourceConfig;
import com.hsogoo.collate.domain.DynamicQuery;
import com.hsogoo.collate.mapper.DataSourceConfigMapper;
import com.hsogoo.collate.mapper.DynamicMapper;
import com.hsogoo.collate.service.CollateConfigManager;
import com.hsogoo.collate.service.DataSourceManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

/**
 * @Author huangsaigang
 * Created @2019-10-27.
 */
@RestController
public class CollateController {

    @Autowired
    private DataSourceManager dataSourceManager;
    @Autowired
    private CollateConfigManager collateConfigManager;
    @Autowired
    private DynamicMapper dynamicMapper;

    /**
     * 添加数据源
     * @param dataSourceConfig
     * @return
     */
    @RequestMapping("/addDataSource")
    public String add(@RequestBody DataSourceConfig dataSourceConfig){

        dataSourceManager.addDataSourceConfig(dataSourceConfig);
        String result = String.format("dataSource[%s] add success", dataSourceConfig.getDataSourceName());
        return result;
    }

    /**
     * 查询数据源
     * @param dataSourceConfig
     * @return
     */
    @RequestMapping("/listDataSources")
    public List<DataSourceConfig> listDataSources(@RequestBody DataSourceConfig dataSourceConfig){
        List<DataSourceConfig> dataSourceConfigs = dataSourceManager.listDataSources();
        return dataSourceConfigs;
    }

    /**
     * 添加对账任务
     * @param collateConfig
     * @return
     */
    @RequestMapping("/addCollateConfig")
    public String addCollateTask(@RequestBody CollateConfig collateConfig){
        collateConfigManager.addCollateConfig(collateConfig);
        return "ok";
    }

    @RequestMapping("/query")
    public String query(@RequestBody CollateQueryReq collateQueryReq){
        DynamicQuery dynamicQuery = new DynamicQuery();
        String sql = "select * from user_info";
        dynamicQuery.setSql(sql);
        dynamicQuery.setDataSourceName(collateQueryReq.getDataSourceName());
        List<Map<String, Object>> result = dynamicMapper.queryData(dynamicQuery);
        return "query end" + result.size();
    }

}
